package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import com.xrit.sunnyday.common.MessageConstant;
import com.xrit.sunnyday.common.PageResult;
import com.xrit.sunnyday.common.QueryPageBean;
import com.xrit.sunnyday.common.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    /*
    远程调用
     */
    @Reference
    private UserService userService;
    /*
    查询所有用户信息并分页
     */
    @RequestMapping("/findPage.do")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult page = userService.findPage(queryPageBean);
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS,page);
    }
    /*
    查询所有角色
     */
    @RequestMapping("/findAllRole.do")
    public Result findAllRole(){
        List<Role> roleList = userService.findAllRole();
        return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,roleList);
    }
    /*
    添加用户
     */
    @RequestMapping("/add.do")
    public  Result add(@RequestBody User u){
        userService.add(u);
        return new Result(true,MessageConstant.ADD_USER_SUCCESS);
    }
    /*
    根据id查询查询所有用户
     */
    @RequestMapping("/delete.do")
    public Result delete(Integer id){
        userService.deleteById(id);
        return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
    }
    /*
    根据id查询
     */
    @RequestMapping("/findById4Edit.do")
    public Result findById4Edit(Integer id){
        User user = userService.findById(id);
        List<Integer> i = userService.findUserRoleById(id);
        List<Role> roleList = userService.findAllRole();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("roleIds",i);
        map.put("roles",roleList);
        map.put("user",user);
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,map);
    }
    /*
    根据id修改
     */
    @RequestMapping("/update.do")
    public Result update(@RequestBody User user){
        userService.update(user);
        return new Result(true,MessageConstant.UPDATE_USER_SUCCESS);
    }
    /*
    从springsecurity取出用户信息
     */
    @RequestMapping("/findByUserName.do")
    public Result findByUserName(){
        //通过securityContextHolde对象获取信息
        org.springframework.security.core.userdetails.User user =(org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
    }
}
